<template>
  <div class="app-container">
    <el-card>
      <div class="header-section">
        <div class="left-buttons">
          <el-button type="primary" icon="Plus" @click="handleAdd">增加</el-button>
          <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
        </div>
        
        <div class="right-form">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="auto">
            <div class="form-row">
              <el-form-item prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable />
              </el-form-item>
              
              <el-form-item prop="account">
                <el-input v-model="queryParams.account" placeholder="请输入学号" clearable />
              </el-form-item>
              
              <el-form-item prop="organization">
                <el-tree-select
                  v-model="queryParams.organization"
                  :data="treeData"
                  :props="treeProps"
                  check-strictly
                  placeholder="请选择组织结构"
                  style="width: 180px;"
                />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item prop="source">
                <el-select v-model="queryParams.source" placeholder="请选择预警来源" clearable style="width: 180px;">
                  <el-option
                    v-for="item in sourceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item prop="interventionLevel">
                <el-select v-model="queryParams.interventionLevel" placeholder="请选择干预级别" clearable style="width: 180px;">
                  <el-option
                    v-for="item in interventionLevelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item prop="warningLevel">
                <el-select v-model="queryParams.warningLevel" placeholder="请选择预警级别" clearable style="width: 180px;">
                  <el-option
                    v-for="item in warningLevelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              </el-form-item>
              
              <el-form-item>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>

      <el-table :data="tableData" style="width: 100%;" :header-cell-style="{ 'background-color': '#f5f7fa' }">
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="organization" label="组织结构" />
        <el-table-column prop="warningLevel" label="预警级别">
          <template #default="{ row }">
            <span :class="getWarningLevelClass(row.warningLevel)">{{ row.warningLevel }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="interventionLevel" label="干预级别" />
        <el-table-column prop="source" label="预警来源" />
        <el-table-column prop="warningTime" label="预警时间" />
        <el-table-column label="评估记录">
          <template #default>
            <el-button type="primary" size="small" style="background-color: #409EFF; color: white;" @click="viewDocument('评估记录')">查看</el-button>
            <el-button type="primary" size="small" style="background-color: #409EFF; color: white;">添加</el-button>
          </template>
        </el-table-column>
        <el-table-column label="干预记录">
          <template #default>
            <el-button type="primary" size="small" style="background-color: #409EFF; color: white;" @click="viewDocument('干预记录')">查看</el-button>
            <el-button type="primary" size="small" style="background-color: #409EFF; color: white;">添加</el-button>
          </template>
        </el-table-column>
        <el-table-column label="预警报告">
          <template #default>
            <el-button type="primary" size="small" @click="viewDocument('预警报告')">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="增加预警" v-model="dialogVisible" width="30%" :close-on-click-modal="false" @close="resetAddForm">
      <el-form :model="form" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="预警来源" prop="source">
          <el-select v-model="form.source" placeholder="请选择预警来源">
            <el-option v-for="item in sourceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警级别" prop="warningLevel">
          <el-radio-group v-model="form.warningLevel">
            <el-radio v-for="item in warningLevelOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预警时间" prop="warningTime">
          <el-date-picker v-model="form.warningTime" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="预警情况" prop="details">
          <el-input type="textarea" v-model="form.details" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文档预览对话框 -->
    <el-dialog v-model="docDialogVisible" :title="currentDocTitle" width="80%" destroy-on-close>
      <div style="height: 600px; overflow-y: auto;">
        <VueOfficeDocx :src="docxSrc" @rendered="rendered" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="docDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { ElMessage } from 'element-plus';
import VueOfficeDocx from '@vue-office/docx';

const queryForm = ref(null);
const queryParams = reactive({
  name: '',
  account: '',
  organization: '',
  source: '',
  interventionLevel: '',
  warningLevel: '',
});

const dateRange = ref([]);

const treeData = ref([
  {
    value: '1',
    label: '组织1',
    children: [
      {
        value: '1-1',
        label: '组织1-1',
      },
    ],
  },
]);

const treeProps = {
  children: 'children',
  label: 'label',
};

const sourceOptions = ref([
  { value: '管理员添加', label: '管理员添加' },
  { value: '调查发现', label: '调查发现' },
  { value: '教师添加', label: '教师添加' },
  { value: '团测发现', label: '团测发现' },
  { value: '其他', label: '其他' },
]);

const interventionLevelOptions = ref([
  { value: '高关怀', label: '高关怀' },
  { value: '危机干预', label: '危机干预' },
  { value: '常规辅导', label: '常规辅导' },
]);

const warningLevelOptions = ref([
  { value: '高度预警', label: '高度预警' },
  { value: '中度预警', label: '中度预警' },
  { value: '轻微预警', label: '轻微预警' },
]);

const initialTableData = ref([
  {
    name: '李明',
    account: 'liming',
    organization: '组织1-1',
    warningLevel: '高度预警',
    interventionLevel: '高关怀',
    source: '管理员添加',
    warningTime: '2025-09-27',
  },
  {
    name: '李四',
    account: 'lisi',
    organization: '组织1-1',
    warningLevel: '中度预警',
    interventionLevel: '危机干预',
    source: '调查发现',
    warningTime: '2023-10-28',
  },
  {
    name: '王五',
    account: 'wangwu',
    organization: '组织1-1',
    warningLevel: '轻微预警',
    interventionLevel: '常规辅导',
    source: '教师添加',
    warningTime: '2023-10-29',
  },
]);

const tableData = ref([...initialTableData.value]);

const addFormRef = ref(null);
const dialogVisible = ref(false);
const docDialogVisible = ref(false);
const docxSrc = ref(null);
const currentDocTitle = ref('');
const currentDocUrl = ref('');

const form = reactive({
  name: '',
  source: '',
  warningLevel: '',
  warningTime: '',
  details: '',
});

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  source: [{ required: true, message: '请选择预警来源', trigger: 'change' }],
  warningLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  warningTime: [{ required: true, message: '请选择预警时间', trigger: 'change' }],
  details: [{ required: true, message: '请输入预警情况', trigger: 'blur' }],
};

onMounted(() => {
  const storedData = sessionStorage.getItem('warningTableData');
  if (storedData) {
    const parsedData = JSON.parse(storedData);
    initialTableData.value = parsedData;
    tableData.value = parsedData;
  }
});

watch(initialTableData, (newData) => {
  sessionStorage.setItem('warningTableData', JSON.stringify(newData));
}, { deep: true });


const handleAdd = () => {
  resetAddForm();
  dialogVisible.value = true;
};

const handleExport = () => {
  // 准备导出数据，不包含表格后三项（评估记录、干预记录、预警报告）
  const exportData = tableData.value.map(item => ({
    姓名: item.name,
    账号: item.account,
    组织结构: item.organization,
    预警级别: item.warningLevel,
    干预级别: item.interventionLevel,
    预警来源: item.source,
    预警时间: item.warningTime
  }));

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, '预警列表');
  
  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  saveAs(blob, `预警列表_${new Date().toLocaleDateString()}.xlsx`);
};

const handleQuery = () => {
  let filteredData = [...initialTableData.value];

  if (queryParams.name) {
    filteredData = filteredData.filter(item => item.name.includes(queryParams.name));
  }
  if (queryParams.account) {
    filteredData = filteredData.filter(item => item.account.includes(queryParams.account));
  }
  if (queryParams.organization) {
    filteredData = filteredData.filter(item => item.organization === queryParams.organization);
  }
  if (queryParams.source) {
    filteredData = filteredData.filter(item => item.source === queryParams.source);
  }
  if (queryParams.interventionLevel) {
    filteredData = filteredData.filter(item => item.interventionLevel === queryParams.interventionLevel);
  }
  if (queryParams.warningLevel) {
    filteredData = filteredData.filter(item => item.warningLevel === queryParams.warningLevel);
  }
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = dateRange.value[0];
    const endDate = dateRange.value[1];
    filteredData = filteredData.filter(item => {
      const itemDate = new Date(item.warningTime);
      return itemDate >= startDate && itemDate <= endDate;
    });
  }

  tableData.value = filteredData;
};

const resetQuery = () => {
  if (queryForm.value) {
    queryForm.value.resetFields();
  }
  queryParams.name = '';
  queryParams.account = '';
  queryParams.organization = '';
  queryParams.source = '';
  queryParams.interventionLevel = '';
  queryParams.warningLevel = '';
  dateRange.value = [];
  tableData.value = [...initialTableData.value];
};

const submitForm = () => {
  if (!addFormRef.value) return;
  addFormRef.value.validate((valid) => {
    if (valid) {
      const newEntry = {
        ...form,
        organization: '组织1-1', // Default organization
        warningTime: new Date(form.warningTime).toLocaleDateString('en-CA'),
        account: 'test' + Math.floor(Math.random() * 1000), // Placeholder account
        interventionLevel: '常规辅导' // Placeholder
      };
      initialTableData.value.unshift(newEntry);
      tableData.value.unshift(newEntry);
      dialogVisible.value = false;
    }
  });
};

const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  form.name = '';
  form.source = '';
  form.warningLevel = '';
  form.warningTime = '';
  form.details = '';
};

const getWarningLevelClass = (level) => {
  switch (level) {
    case '高度预警':
      return 'warning-level-high';
    case '中度预警':
      return 'warning-level-medium';
    case '轻微预警':
      return 'warning-level-low';
    default:
      return '';
  }
};

// 查看文档方法
const viewDocument = async (docType) => {
  currentDocTitle.value = docType;
  // 根据文档类型设置URL
  const baseUrl = '/docs/';
  let docPath = '';
  
  switch (docType) {
    case '评估记录':
      docPath = baseUrl + '评估记录.docx';
      break;
    case '干预记录':
      docPath = baseUrl + '干预记录.docx';
      break;
    case '预警报告':
      docPath = baseUrl + '预警报告.docx';
      break;
    default:
      ElMessage.error('文档不存在');
      return;
  }
  
  try {
    // 显示文档预览对话框
    docDialogVisible.value = true;
    
    // 加载docx文件
    const response = await fetch(docPath);
    if (!response.ok) {
      throw new Error(`无法加载文档: ${response.statusText}`);
    }
    
    docxSrc.value = await response.arrayBuffer();
    
    ElMessage({
      message: '文档加载成功',
      type: 'success'
    });
  } catch (error) {
    console.error('文档加载失败:', error);
    ElMessage.error(`文档加载失败: ${error.message}`);
  }
};

const rendered = () => {
  console.log("渲染完成");
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  border: none;
  box-shadow: none;
}

.app-container > .el-row > .el-col > .el-card {
  border: none;
  box-shadow: none;
}

:deep(.el-card) {
  border: none;
  box-shadow: none;
}

:deep(.el-table) {
  border: none;
  box-shadow: none;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  gap: 40px;
}

.left-buttons {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.right-form {
  flex: 1;
  padding-left: 200px;
  min-width: 0;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
  gap: 10px;
  align-items: flex-end;
}



:deep(.el-form-item) {
  margin-bottom: 10px;
  margin-right: 0;
}

:deep(.el-input),
:deep(.el-select) {
  width: 180px;
}

.warning-level-high {
  background-color: red;
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
}

.warning-level-medium {
  background-color: yellow;
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
}

.warning-level-low {
  background-color: green;
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
}
</style>
